/**
 * 文件名    ： NovelCrawController.java
 * 版权       : XX科技有限公司。
 * 描述       : <描述>
 * 修改时间：2018年11月14日
 * 修改内容：<修改内容>
 */
package com.example.demo.application.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.application.common.MyConstants;
import com.example.demo.application.common.MyConstantsRespone;
import com.example.demo.application.common.base.ResultMsg;
import com.example.demo.application.model.LoginUserEntity;
import com.example.demo.application.model.UserCacheEntity;
import com.example.demo.application.model.UserRepeateEntity;
import com.example.demo.application.myredis.RedisHelper;
import com.example.demo.application.service.IUserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(description = "用户登录接口")
@RestController
@EnableAutoConfiguration
@RequestMapping(path = "/noauth/userlogin")
public class LoginController {

	protected final Logger log = LoggerFactory.getLogger(LoginController.class);

	@Resource(name = "userService")
	private IUserService userService;

	/**
	 * <一句话功能简述> 下载小说文件 <功能详细描述>
	 * 
	 * @param form
	 * @throws Exception
	 * @see [类、类#方法、类#成员]
	 */
	@ApiOperation(value = "登录", notes = "登录, 以后再改成cas框架的 sso单点登录 ")
	@RequestMapping(path = "/login", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg login(HttpServletResponse response,HttpServletRequest request, @RequestBody LoginUserEntity form) throws Exception {
		ResultMsg modelMap = new ResultMsg();
		// 登录
		LoginUserEntity user = (LoginUserEntity) userService.findUserById(form);
		if (null == user) {
			//登录失败
			modelMap.setCode(MyConstantsRespone.fail);
			return modelMap;
		}
		//查询是否账号登录过
		String lastToken = RedisHelper.get(MyConstants.ACCOUNT_TOKEN + user.getAccount());
		if (StringUtils.isNotBlank(lastToken)) {
			//删除 前用户，将token值消息改成提示 异地登录
			RedisHelper.delAllObject(MyConstants.LOGIN_USER + lastToken);
			RedisHelper.delAllObject(MyConstants.ACCOUNT_TOKEN + lastToken);
			UserCacheEntity uCahcheDel = new UserCacheEntity();
			uCahcheDel.setId(user.getId());
			uCahcheDel.setName("账号异地登录");
			uCahcheDel.setAccount("账号异地登录");
			// 失效时间15分钟
			RedisHelper.set(MyConstants.LOGIN_DENCY + lastToken, MyConstants.LOGIN_DENCY_STATUS, 60 * 15 * 1);
//				RedisHelper.addObject(MyConstants.LOGIN_USER + lastToken, uCahcheDel, 60 * 30 * 1);
		}
		if (StringUtils.isNotBlank(user.getToken())) {
			
			// token令牌
//			response.setHeader(MyConstants.TOKEN_AUTH, user.getToken());
//			request.setAttribute(MyConstants.TOKEN_AUTH, user.getToken());
			// 失效时间60*60*6秒
			UserCacheEntity uCahche = new UserCacheEntity();
			uCahche.setId(user.getId());
			uCahche.setName(user.getName());
			uCahche.setAccount(user.getAccount());
			RedisHelper.addObject(MyConstants.LOGIN_USER + user.getToken(), uCahche, 60 * 60 * 6);
			// 记录账号对应的 token,判断是否 账号多地区登录；
			RedisHelper.set(MyConstants.ACCOUNT_TOKEN + user.getAccount(), user.getToken(), 60 * 60 * 6);
			modelMap.setCode(MyConstantsRespone.success);
			modelMap.setData(user);
		} else {
			modelMap.setCode(MyConstantsRespone.fail);
		}
		return modelMap;
	}

	@ApiOperation(value = "登出", notes = "登出")
	@RequestMapping(path = "/logout", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg logout(HttpServletRequest request, @RequestBody LoginUserEntity form) throws Exception {
		ResultMsg modelMap = new ResultMsg();
		String token = request.getHeader(MyConstants.TOKEN_AUTH);
		List<UserCacheEntity> uCahcheDel  = (List<UserCacheEntity>) RedisHelper.getAllObject(MyConstants.LOGIN_USER + token);
		//判断 用户，删除
		if (null != uCahcheDel && uCahcheDel.size() > 0 ) {
			RedisHelper.delAllObject(MyConstants.LOGIN_USER + token);
			RedisHelper.delAllObject(MyConstants.ACCOUNT_TOKEN + token);
		}
		modelMap.setCode(MyConstantsRespone.success);
		return modelMap;

	}

	/**
	 * <功能>  修改密码，修改完后 不返回token,
	 * <详细描述> 
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 * @see [类、类#方法、类#成员]
	 */
	@ApiOperation(value = "更新密码", notes = "更新密码")
	@RequestMapping(path = "/update", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg update(HttpServletRequest request, HttpServletResponse response, @RequestBody UserRepeateEntity form)
			throws Exception {
		ResultMsg modelMap = new ResultMsg();
		String token = request.getHeader(MyConstants.TOKEN_AUTH);
		List<UserCacheEntity> uCahcheDel  = (List<UserCacheEntity>) RedisHelper.getAllObject(MyConstants.LOGIN_USER + token);
		//判断 用户，删除
		if (null != uCahcheDel && uCahcheDel.size() > 0 ) {
			RedisHelper.delAllObject(MyConstants.LOGIN_USER + token);
			RedisHelper.delAllObject(MyConstants.ACCOUNT_TOKEN + token);
		}
		///有多个，则 失败，重新登录
		if (uCahcheDel.size() > 1 || uCahcheDel.size() < 0) {
			modelMap.setCode(MyConstantsRespone.fail);
			return modelMap;
		}
		form.setAccount(uCahcheDel.get(0).getAccount());
		// 更新
		LoginUserEntity user = userService.update(form);
		if (StringUtils.isNotBlank(user.getToken())) {
//			response.setHeader(MyConstants.TOKEN_AUTH, user.getToken());
			modelMap.setCode(MyConstantsRespone.success);
		} else {
			modelMap.setCode(MyConstantsRespone.fail);
		}
//		Cookie mycookies = new Cookie("sessionid", sid);
//		mycookies.setMaxAge(-1);
		// 总结：domain表示的是cookie所在的域，默认为请求的地址，如网址为www.study.com/study，那么domain默认为www.study.com。而跨域访问，如域A为t1.study.com，域B为t2.study.com，那么在域A生产一个令域A和域B都能访问的cookie就要将该cookie的domain设置为.study.com；如果要在域A生产一个令域A不能访问而域B能访问的cookie就要将该cookie的domain设置为t2.study.com。注意：一般在域名前是需要加一个"."的，如"domain=.study.com"。
//		mycookies.setDomain("locahost");
//		mycookies.setPath("/");
//		response.addCookie(mycookies);
		// 登录信息放 头部，比cookie安全；
		return modelMap;
	}

	@ApiOperation(value = "注册", notes = "注册")
	@RequestMapping(path = "/register", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg register(HttpServletResponse response, @RequestBody LoginUserEntity form) throws Exception {
		ResultMsg modelMap = new ResultMsg();
		userService.addUser(form);
		modelMap.setCode(MyConstantsRespone.success);
		return modelMap;
	}

}
